package chatbot.controller;

import chatbot.entity.Step;
import chatbot.enums.ExpressionConstant;
import chatbot.enums.StepNameConstant;
import chatbot.service.Parsescript;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.lang.reflect.Array;
import java.util.*;

/**
 前端页面的路由
 */
@RequestMapping("/chat")
@Controller
public class ChatController {
    private static ObjectMapper objectMapper=new ObjectMapper();
    @GetMapping("/index")
    private String index(Model model){
        model.addAttribute("stepname",StepNameConstant.WELCOMEPRO.getName());
        model.addAttribute("welcome", Parsescript.getStepValue(StepNameConstant.WELCOMEPRO.getName(), ExpressionConstant.SPEAK.getName()));
        return "index";//返回freemaker的名字
    }

    @ResponseBody
    @PostMapping("/msg")
    private Map postData(String stepname, String msg,String chatlist) throws JsonProcessingException {
        HashMap<String,Object> map=new HashMap<>();
        map.put("refresh","0");
        String[] chatArray=objectMapper.readValue(chatlist,String[].class);
        ArrayList<String> chatList = new ArrayList<>(Arrays.asList(chatArray));
        //在preStepName下寻找branch
        Step step1 = Parsescript.stepHashMap.get(stepname);
        Step nextStep=Parsescript.searchStepBybranch(msg,step1);
        chatList.add(msg);
        if(nextStep==null){
            chatList.add("抱歉,你的问题没找到");
            map.put("refresh","1");
        }else{
            String nextmsg=Parsescript.getStepValue(nextStep.getStepName(),ExpressionConstant.SPEAK.getName());
            chatList.add(nextmsg);
            Object[] lastStep=Parsescript.getRestStep(nextStep);
            if(lastStep[0]==null){
                chatList.add((String)lastStep[1]);
                map.put("refresh","1");
            }else{
                stepname=((Step)lastStep[0]).getStepName();
            }
        }
        StringBuilder sb=new StringBuilder();
        for(int i=0;i<chatList.size();i++){
            sb.append(chatList.get(i));
            sb.append(";");
        }
        if(sb.length()>1){
            sb.deleteCharAt(sb.length()-1);
        }
        //向前端返回 stepname
        map.put("code","200");
        map.put("msg","返回成功");
        map.put("stepname",stepname);
        map.put("chatmsg",sb.toString());
        return map;
    }
}
